package user

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryUserInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryUserInfoLogic {
	return &QueryUserInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryUserInfoLogic) QueryUserInfo(in *pb.QueryUserInfoReq) (*pb.QueryUserInfoResp, error) {
	// 1.query user info to db
	infoBO := bo.UserInfoBO{
		UserId: in.UserId,
	}
	userEntity, err := mapper.NewUserMapper().SelectOne(l.svcCtx.DBEngin, infoBO)
	if err != nil {
		if err.Error() == "record not found" {
			return nil, excption.NewErrCode(constans.UserNoExistError)
		}
		logx.Errorf("select user entity err:%s", err.Error())
		return nil, err
	}
	// 2.query role info
	sysRoleEntityArr, sysRoleEntityArrErr := mapper.NewRoleMapper().SelectListByUserId(l.svcCtx.DBEngin, in.UserId)
	if sysRoleEntityArrErr != nil {
		return nil, err
	}
	var roleArr []*pb.RoleInfoResp
	if len(sysRoleEntityArr) > 0 {
		for _, v := range sysRoleEntityArr {
			roleArr = append(roleArr, &pb.RoleInfoResp{
				RoleId:   v.RoleId,
				RoleName: v.RoleName,
				RoleDesc: v.Remark,
			})
		}
	}
	// 3.query dept info...
	deptEntity, selectDeptByUserIdErr := mapper.NewDeptMapper().SelectDeptByUserId(l.svcCtx.DBEngin, in.UserId)
	if selectDeptByUserIdErr != nil {
		return nil, selectDeptByUserIdErr
	}
	resp := new(pb.QueryUserInfoResp)
	if deptEntity.DeptId > 0 {
		resp.DeptId = deptEntity.DeptId
		resp.DeptName = deptEntity.Name
	}
	// 4.return obj ..
	resp.RoleArr = roleArr
	resp.UserId = userEntity.UserId
	resp.UserName = userEntity.Username
	resp.Email = userEntity.Email
	resp.Mobile = userEntity.Mobile
	resp.Status = strconv.Itoa(userEntity.Status)
	resp.CreateTime = userEntity.CreateTime.Format("2006/1/02 15:04:05")
	resp.UpdateTime = resp.CreateTime
	return resp, nil
}
